/*
 * @Descripttion: 
 * @Author: whyjs
 * @Date: 2022-05-16 19:26:59
 * @LastEditors: whyjs
 * @LastEditTime: 2023-02-02 19:36:00
 */
var login_docDemoTabBrief=0
//验证码
var _CaptchaKey = ''
var loginObject = {
  $this: null,
  form: null,
  formV: null,
  formVCode: null,
  formForget: null,
  formShortMessage: null,
  dataObj: null,
  passwordBox: null,
  changepassBox: null,
  _init: function () {
    $this = this;
    $this._initForm(); //初始化表单校验规则
    $this._initSubmit(); //登录
    $this._initShortMessageSubmit(); //登录
    $this._getShortMessageVerificationCode();//获取与短信验证码
    $this._define();//选择登陆账号
    $this._forget();//忘记密码校验规则
    $this._forgetConfirm();//忘记密码提交
    $this._forGetPhoneCode();//忘记密码手机验证码
    $this._changeComfirm();//修改密码提交
    $this._changeforget();//修改密码校验规则

  },
  // 修改密码提交
  _changeComfirm: function(){
    $(document).on('click', "#changeConfitm", function () {
      if ($this.changeformForget.form()) {
        var newpass = $('#newpass').val()
        var confirmNew = $('#confirmNew').val()
        if(newpass != confirmNew){
          addErrorTips('changePswConfirmBox', '密码不一致，请重新输入')
          return
        }else{
          addErrorTips('changePswConfirmBox', '')
        }
        var reg = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}$/
        if (!reg.test($('#newpass').val())&&$('#newpass').val()) {
          // layer.msg('密码必须是6-16位，至少包含英文字母、数字、字符中2种');
          addErrorTips('changenewpass', '密码必须是8-16位，需同时包含大写字母、小写字母、数字、特殊字符4种')
          return
        } else {
          addErrorTips('changenewpass', '')
        }
        var reserparams = {
          account:$('#mobile').val(),
          oldPassword:sha256_digest($('#pwd').val()),
          newPassword:sha256_digest($("#newpass").val()),
        }
        fnBase.ajaxJson({
          type: "post",
          url: "/goldnet-enterprise-client/sysUser/updatePassword",
          data: reserparams,
          success: function (response) {
            //提交成功处理
            // //console.log(response);
            if (response.code == 200) {
              layer.msg('修改成功,请重新登入！', {
                time: 2000
              });
              setTimeout(function(){
                layer.close($this.changepswBox);
                window.location.reload();
              },3000)
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            //提交失败处理
            forGetCode()
            //console.log(XMLHttpRequest, textStatus, errorThrown);
          },
        });
      }
    })
  },
  //忘记密码提交
  _forgetConfirm: function () {
    
    $(document).on('click', '#goToConfitm', function () {
      if ($this.formForget.form()) {
        var forGetPsw = $('#forGetPsw').val()
        var forGetPswConfirm = $('#forGetPswConfirm').val()
        if (forGetPsw != forGetPswConfirm) {
          // layer.msg('密码不一致，请重新输入');forGetPswConfirmBox
          addErrorTips('forGetPswConfirmBox', '密码不一致，请重新输入')
          return
        } else {
          addErrorTips('forGetPswConfirmBox', '')
        }
        var reg = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}$/
        if (!reg.test($('#forGetPsw').val())) {
          // layer.msg('密码必须是6-16位，至少包含英文字母、数字、字符中2种');
          addErrorTips('forGetPswBox', '密码必须是8-16位，需同时包含大写字母、小写字母、数字、特殊字符4种')
          return
        } else {
          addErrorTips('forGetPswBox', '')
        }
        var photoCodeVal = $("#imgCode").val();
        var params = {
          account: $('#user').val(),
          newPassword: sha256_digest($("#forGetPsw").val()),
          phone: $('#phone').val(),
          smsCode: $('#phoneCode').val(),
          tenantId:channelFindObj('tenantId')
        }
        fnBase.ajaxJson({ 
          type: "post",
          url: "/goldnet-enterprise-client/sysUser/resetPassword",
          data: params,
          headers: {
            "Captcha-Key": _CaptchaKey,
            "Captcha-Code": photoCodeVal,
          },
          success: function (response) {
            //提交成功处理
            // //console.log(response);
            if (response.code == 200) {
              layer.msg('密码修改成功', {
                time: 3000
              });
              layer.close($this.passwordBox);
              reloadCodeImg();
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            //提交失败处理
            forGetCode()
            //console.log(XMLHttpRequest, textStatus, errorThrown);
          },
        });
      }
    })
  },
  //忘记密码校验
  _forget: function () {
    $this.formForget = $('#forGetForm').validate({
      errorPlacement: function (error, element) {
        error.appendTo(element.parent());
      },
      rules: {
        user: {
          required: true,
        },
        phone: {
          required: true,
        },
        imgCode: {
          required: true,
        },
        phoneCode: {
          required: true,
        },
        forGetPsw: {
          required: true,
          required: true,
          passwordNew:true,
          passwordNewLx:true,
          similar:'#user'
        },
        forGetPswConfirm: {
          required: true,
        },
      },
      messages: {
        phone: {
          required: '请输入账号绑定的手机号码',
          maxlength: '最大长度11'
        },
        user: {
          required: '请输入您的用户名',
        },
        imgCode: {
          required: '请输入图形验证码',
        },
        phoneCode: {
          required: '请输入验证码',
        },
        forGetPsw: {
          required: '请输入新密码'
        },
        forGetPswConfirm: {
          required: '请输入确认密码',
        },
      }
    })
  },
   // 修改密码校验
   _changeforget: function () {
    $this.changeformForget= $('#changeforGetForm').validate({
      errorPlacement: function (error, element) {
        error.appendTo(element.parent());
      },
      rules: {
        oldpass: {
          required: true,
        },
        newpass: {
          required: true,
          passwordNew:true,
          passwordNewLx:true,
          similar:'#mobile'
          

        },
        confirmNew: {
          required: true,
        },
      },
      messages: {
        oldpass:{
          required: '请输入原密码',
        },
        
        newpass: {
          required: '请输入新密码',
          // similar:'相似度不能超过80%'
        },
        confirmNew: {
          required: '请输入确认密码',
        },
      }
    })
  },
  //密码登录
  _initForm: function () {
    $this.formV = $("#formWrapper").validate({
      ignore: "",
      errorPlacement: function (error, element) {
        error.appendTo(element.parent());
      },
      rules: {
        mobile: {
          required: true,
          //mobile:true,
          //maxlength: 11
        },
        pwd: {
          required: true,
        },
        photo_code: {
          required: true,
        },
      },
      messages: {
        mobile: {
          required: '请输入用户账号',
          //maxlength:'最大长度11'
        },
        pwd: {
          required: '请输入正确的密码',
        },
        photo_code: {
          required: '请输入正确的图形验证码'
        },

      }
    });
    // 验证码登录
    $this.formVCode = $("#formWrapperCode").validate({
      ignore: "",
      errorPlacement: function (error, element) {
        error.appendTo(element.parent());
      },
      rules: {
        mobile_code: {
          required: true,
          mobile: true,
          maxlength: 11
        },
        photo_code: {
          required: true,
        },
        sms_code: {
          required: true,
        }
      },
      messages: {
        mobile_code: {
          required: '请输入用户手机号码',
          maxlength: '最大长度11'
        },
        photo_code: {
          required: '请输入正确的图形验证码',
        },
        sms_code: {
          required: '请输入正确的短信验证码',
        }

      }
    });
  },
_initSubmit: function () {
  $("#photoCodeVal").keydown(function (e) {
    if (e.keyCode == 13 && $("#login_btn").css("pointer-events") != 'none') {
      $('#login_btn').click()
    }
  });
  var that = this
  $(document).on('click', '#login_btn', function () {
    if ($this.formV.form()) {
      var photoCodeVal = $("#photoCodeVal").val();
      var params = {
        "account": $("#mobile").val(),
        "password": $("#pwd").val(),
        // "password":sha256_digest($("#pwd").val()),
        //tenantId:channelFindObj('tenantId')
      };
      $("#login_btn").css({ "pointer-events": "none", 'background-color': '#E3E3E3' })
      $.ajax({
        "type": "post",
        //url: "/goldnet-enterprise-client/sysUser/userLogin",
        // url: "/goldnet-enterprise-client/v2/auth/users/account-login",
        "url": "/gongyinglian/LoginController",
        "dataType":"json",
        "data": params,
        "success": function (response) {
          $("#login_btn").attr("style", "")
          console.log("成功：" + response.toString())
          console.log("状态码：" + response.code)

          //提交成功处理
          if (response.code == 200) {
	        var role = response.role
            if(role == 1){//核心企业
                window.location.href = "/gongyinglian/main/index1.jsp";
            }else if(role == 2){//商业银行
	            window.location.href = "/gongyinglian/main/index2.jsp";
            }else if(role == 3){//链条企业
	            window.location.href = "/gongyinglian/main/index3.jsp";
            }

          }
        },
        "error": function (XMLHttpRequest, textStatus, errorThrown) {
          $("#login_btn").attr("style", "")
          //提交失败处理
          console.log(XMLHttpRequest, textStatus, errorThrown);
          alert("用户名或密码错误！")
          //reloadCodeImg()//刷新验证码
        },
      });
    }
  });
},
  _define: function () {
    $(document).on('click', '#definego', function () {
      var i = $('#layui-alert').find('input[name="s"]:checked').parent('li').index()
      //console.log(i)
      if (i == -1) {
        layer.msg('请选择登陆的账号');
      } else {

        setCookie("GoldNet-Auth", $this.dataObj[i].tokenInfo.accessToken);
        //用户状态
        var accountStatus = $this.dataObj[i].accountInfo.accountStatus
        setCookie("accountStatus", accountStatus);
        var info = $this.dataObj[i].accountInfo;
        var userInfo = {
          "user_id": info.userId,
          "user_name": info.userName,
          "enterprise_id": info.enterpriseId,
          "enterpriseName": info.enterpriseName,
          "phone": info.phone,
          "account": info.account,
          "avatar": info.avatar
        };
        setCookie("userInfo", JSON.stringify(userInfo));
        // 工作组
        if(login_docDemoTabBrief == 0){
          // 不满足密码规则
          var reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[A-Z])(?=.*\d)(?=.*[!.@#$%^&*()\-+])(?!.*(.)\1{2})(?!.*(?:012|123|234|345|456|567|678|789))[a-zA-Z0-9!.@#$%^&*()\-+]{8,}$/;
          if(!reg.test($("#pwd").val())){
            fnBase.token = $this.dataObj[i].tokenInfo.accessToken;
            $('#oldpass').val($('#pwd').val())
              $this.changepassBox = layer.open({
              type: 1,
              title: '修改密码',
              closeBtn: 1,
              shadeClose: true,
              content: $('#changepswBox')
            });
            reloadCodeImg();
            return
          }
        }
        
        switch (parseInt(accountStatus)) {
          //注册未认证  
          case 12:
            window.location.href = "/avic/reg/auth";
            break;
          // 绑定ukey  
          case 7:
            window.location.href = "/avic/reg/certification";
            break;
          // 审核通过  
          case 0:
            window.location.href = "/hx/home/homepage";
            break;
          // 待审核  
          case 5:
            window.location.href = "/avic/reg/examine";
            break
          case 11:
            window.location.href = "/avic/reg/examine?revoke=1";
            break;
          case 6:
            window.location.href = "/avic/reg/examine?revoke=1";
            break;
          //审核拒绝  
          case 10:
            window.location.href = "/avic/reg/auth";
            break;
          case 13:
            window.location.href = "/hx/home/homepage";
            break;


          default:
            break;
        }
      }
    })
  },
  // 手机号登陆
  _initShortMessageSubmit: function () {
    $("#sms_code").keydown(function (e) {
      if (e.keyCode == 13&&$("#login_btn_code").css("pointer-events")!='none'){
        $('#login_btn_code').click()
      } 
    });

    $(document).on('click', '#login_btn_code', function () {

      //console.log('123456;')
      if ($this.formVCode.form()) {
        var photoCodeVal = $("#photo_code").val();
        var params = {
          "phone": $("#mobile_code").val(),
          "smsCode": $('#sms_code').val(),
          tenantId:channelFindObj('tenantId')
        };
        $("#login_btn_code").css({"pointer-events":"none",'background-color':'#E3E3E3'})
        fnBase.ajaxJson({
          type: "post",
          url: "/goldnet-enterprise-client/v2/auth/users/smsCode-login",
          data: params,
          headers: {
            "Captcha-Key": _CaptchaKey,
            "Captcha-Code": photoCodeVal,
          },
          success: function (response) {
            $("#login_btn_code").attr("style","")
            //提交成功处理
            //console.log(response);
            if (response.code == 200) {
              if (response.data.length > 1) {
                var laytpl = layui.laytpl;
                $this.dataObj = response.data
                var getTpl = document.getElementById('demo').innerHTML
                view = document.getElementById('layui-alert');
                laytpl(getTpl).render($this.dataObj, function (html) {
                  view.innerHTML = html;
                });
                //console.log(response.data)
                layer.open({
                  type: 1,
                  title: '选择账号',
                  closeBtn: 1,
                  shadeClose: true,
                  content: $('#layui-alertBox')
                });
              } else {
                setCookie("GoldNet-Auth", response.data[0].tokenInfo.accessToken);
                //用户状态
                var accountStatus = response.data[0].accountInfo.accountStatus
                setCookie("accountStatus", accountStatus);
                var info = response.data[0].accountInfo;
                var userInfo = {
                  "user_id": info.userId,
                  "user_name": info.userName,
                  "enterprise_id": info.enterpriseId,
                  "enterpriseName": info.enterpriseName,
                  "phone": info.phone,
                  "account": info.account,
                  "avatar": info.avatar
                };
                var workGroupInfo = {
                  workGroup: '',	//  工作组id	
                  workGroupName: ''
                }
                if (response.data[0].workGroupInfo) {
                  workGroupInfo = {
                    workGroup: response.data[0].workGroupInfo.workGroup,	//  工作组id	
                    workGroupName: response.data[0].workGroupInfo.workGroupName
                  }
                }
                setCookie("userInfo", JSON.stringify(userInfo));
                setCookie("workGroupInfo", JSON.stringify(workGroupInfo));

                switch (parseInt(accountStatus)) {
                  //注册未认证  
                  case 12:
                    window.location.href = "/avic/reg/auth";
                    break;
                  // 绑定ukey  
                  case 7:
                    window.location.href = "/avic/reg/certification";
                    break;
                  // 审核通过  
                  case 0:
                    window.location.href = "/hx/home/homepage";
                    break;
                  // 待审核  
                  case 5:
                    window.location.href = "/avic/reg/examine";
                    break;
                  case 11:
                    window.location.href = "/avic/reg/examine?revoke=1";
                    break;
                  case 6:
                    window.location.href = "/avic/reg/examine?revoke=1";
                    break;
                  //审核拒绝  
                  case 10:
                    window.location.href = "/avic/reg/auth";
                    break;
                  case 13:
                    window.location.href = "/hx/home/homepage";
                    break;

                  default:
                    break;
                }
              }


            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            $("#login_btn_code").attr("style","")
            //提交失败处理
            // //console.log(XMLHttpRequest, textStatus, errorThrown);
            shortMessageCode()
          },
        });
      };
    })
  },
  // 忘记密码手机验证码
  _forGetPhoneCode: function () {
    $(document).on('click', '#forGetphoneNum', function () {
      var phone = $("#phone").val()
      var account = $('#user').val()
      if (account == '') {
        layer.msg('请输入您的用户名');
        return
      }
      if (phone == '') {
        layer.msg('请输入账号绑定的手机号码');
        return
      }
      // layer.msg('验证码发送成功')
      // timeDownFn('forGetphoneNum',60)
      fnBase.ajaxJson({
        type: "get",
        url: "/goldnet-enterprise-client/sysUser/sendValidateByAccount",
        data: {
          account: account,
          phone: phone,
          tenantId:channelFindObj('tenantId')
        },
        success: function (response) {
          layer.msg('验证码发送成功')
          timeDownFn('forGetphoneNum', 60)

          //console.log(response)
          // setInterval
        }
      });
    })
  },
  // 获取手机验证码
  _getShortMessageVerificationCode: function () {
    $(document).on('click', '#getVcode', function () {
      var phone = $("#mobile_code").val()
      //console.log(phone)
      if (phone == '') {
        layer.msg('请输入手机号');
        return
      } else {
        //console.log('手机号不为空')
      }

      fnBase.ajaxJson({
        type: "get",
        url: "/goldnet-enterprise-client/v2/auth/users/smsCode",
        data: {
          phone: phone,
          tenantId:channelFindObj('tenantId')
        },
        success: function (response) {
          layer.msg('验证码发送成功')
          timeDownFn('getVcode', 60)
          //console.log(response)
          // setInterval
        }
      });
    })
  },
  // 密码超过6次
  openSix:function () {
    layer.confirm('密码输入错误达到6次，账号已锁定，您需要通过忘记密码进行重新设置。', {
      title:'提示',
      skin: 'confirm-box',
      btn: ['立即设置','取消'],
      skin: 'footBtn-box'
    }, function(index){
      openForGet()
      layer.close(index)
    });
  }
}



//初始化
layui
  .config({ base: "https://ljyh-web.aero-credit.com/avic/modules/" })
  .extend({

  })
  .use(["form"], function () {
    // FormValidation.init()
    loginObject._init();
    reloadCodeImg();
    // shortMessageCode()
    // forGetCode()
  });
  
// $(document).ready(function(){
//   loginObject._init();
//   reloadCodeImg();
//   shortMessageCode()
// })
layui.use('element', function () {
  var element = layui.element;
  element.on('tab(docDemoTabBrief)', function (data) {
    //console.log(data);
    if (data.index == 0) {
      login_docDemoTabBrief = 0
      reloadCodeImg()
    } else if (data.index == 1) {
      shortMessageCode()
      login_docDemoTabBrief = 1
    }
  });
});

//刷新验证码
var reloadCodeImg = function () {

  // var kaptchaKeyUrl = $("#kaptchaKeyId").attr("data-src");
  // var newUri = kaptchaKeyUrl + "&time=" + new Date().getTime();
  var uri = fnBase.baseUrl + "/goldnet-auth/oauth/captcha";

  $.get(uri, function (res) {
    // setCookie("Captcha-Key",res.key)
    _CaptchaKey = res.key
    $("#kaptchaKeyId").attr("src", res.image);
  })
};
// 手机号登陆图形验证
var shortMessageCode = function () {
  var uri = fnBase.baseUrl + "/goldnet-auth/oauth/captcha";
  $.get(uri, function (res) {
    // setCookie("Captcha-Key",res.key)
    _CaptchaKey = res.key
    $("#shortMessage").attr("src", res.image);
  })
};
// 忘记密码图形验证
var forGetCode = function () {
  var uri = fnBase.baseUrl + "/goldnet-auth/oauth/captcha";
  $.get(uri, function (res) {
    // setCookie("Captcha-Key",res.key)
    _CaptchaKey = res.key
    $("#forGetImg").attr("src", res.image);
  })
};
// 密码登录---密码显隐
var ExplicitImplicit = function () {
  $('#look').show();
  $('#unlook').hide();
  var type = $('#pwd').attr('Type')
  //console.log(type)
  if (type == 'password') {
    $('#pwd').attr('Type', 'text')
    $('#look').show();
    $('#unlook').hide();
  } else {
    $('#pwd').attr('Type', 'password')
    $('#unlook').show();
    $('#look').hide();
  }
};
// 忘记密码---密码显隐
var forGetExplicitImplicit = function (id) {
  //console.log(id)
  var type = $('#' + id).attr('Type')
  //console.log(type)
  if (type == 'password') {
    $('#' + id).attr('Type', 'text')
  } else {
    $('#' + id).attr('Type', 'password')
  }
};
var colse = function () {
  layer.closeAll()
};
var openForGet = function () {
  forGetCode()
  $("#forGetForm")[0].reset();
  addErrorTips('forGetPswConfirmBox', '')
  addErrorTips('forGetPswBox', '')
  layui.form.render();
  // $('#user').val('')
  // $('#phone').val('')
  // $('#imgCode').val('')
  // $('#phoneCode').val('')
  // $('#forGetPsw').val('')
  // $('#forGetPswConfirm').val('')
  $this.passwordBox = layer.open({
    type: 1,
    title: '找回密码',
    closeBtn: 1,
    shadeClose: true,
    content: $('#resetpswBox')
  });

};
//密码强度
var pwdstrength = function () {
  //密码校验
  var pwdVal = $("#forGetPsw").val();
  //密码强度正则
  // var strongRegex = new RegExp("^((?=.*[A-Z])|(?=.*[a-z]))(?=.*[0-9])(?=.*[~!@#$%^&*?]).*$", "g");
  var strongRegex = new RegExp("^(?=.{3,})(?=.*[A-Za-z])(?=.*[0-9])(?=.*\\W).*$", "g");
  var mediumRegex = new RegExp("^(?=.{3,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
  var enoughRegex = new RegExp("(?=.{3,}).*", "g");

  if (false == enoughRegex.test(pwdVal)) {
    //只有一种字母时显示为低 
    $(".pwd_strength_main .left").css("background", "#FF6C6C");
    $(".pwd_strength_main .center").css("background", "#E3E3E3");
    $(".pwd_strength_main .right").css("background", "#E3E3E3");

  } else if (strongRegex.test(pwdVal)) {
    //密码为字母数字特殊字符三项都包括,强度最强 
    $(".pwd_strength_main .left").css("background", "#FF6C6C");
    $(".pwd_strength_main .center").css("background", "#FF6C6C");
    $(".pwd_strength_main .right").css("background", "#FF6C6C");
  } else if (mediumRegex.test(pwdVal)) {
    //密码为字母、数字、特殊字符三项中有两项，强度是中等 
    $(".pwd_strength_main .left").css("background", "#FF6C6C");
    $(".pwd_strength_main .center").css("background", "#FF6C6C");
    $(".pwd_strength_main .right").css("background", "#E3E3E3");
  } else {
    //默认为弱
    $(".pwd_strength_main .left").css("background", "#FF6C6C");
    $(".pwd_strength_main .center").css("background", "#E3E3E3");
    $(".pwd_strength_main .right").css("background", "#E3E3E3");
  }
  if (pwdVal == '') {
    $(".pwd_strength_main .left").css("background", "#E3E3E3");
    $(".pwd_strength_main .center").css("background", "#E3E3E3");
    $(".pwd_strength_main .right").css("background", "#E3E3E3");
  }
};
var timeDownFn = function (id, n) {
  var m = n - 1;
  setTimeout(function () {
    if (m == 0) {
      $("#" + id).html("重新获取验证码");
      $("#" + id).css('pointer-events', 'auto')
      $("#" + id).attr('style', '')
    } else {
      $("#" + id).html(m + "秒后重新获取");
      $("#" + id).css('pointer-events', 'none')
      $("#" + id).css('background-color', '#E3E3E3')
      timeDownFn(id, m);
    }
  }, 1000)
}
//远程验证添加错误提示
var addErrorTips = function (parentNode, msg) {
  if ($("#" + parentNode + " .error_tips").length > 0) {
    $("#" + parentNode + " .error_tips").text(msg);
  } else {
    var error_tips = '<div class="error_tips">' + msg + '</div>';
    $("#" + parentNode).append(error_tips);
  }
};
